<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="类型名称" prop="typeName">
        <el-input
          v-model="queryParams.typeName"
          placeholder="请输入类型名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['shopping:goodsType:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Refresh"
          @click="handleRefresh"
          >刷新缓存</el-button
        >
      </el-col>
        <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
        :columns="columns"
      ></right-toolbar>
    </el-row>

    <el-table
      ref="tableRef"
      :key="tableKey"
      v-loading="loading"
      :data="goodsTypeList"
      @selection-change="handleSelectionChange"
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      lazy
      :load="loadNode"
    >
    <el-table-column
        label="ID"
        align="center"
        prop="id"
        v-if="columns[1].visible"
      />
      <el-table-column
        label="类型名称"
        align="center"
        prop="typeName"
        v-if="columns[0].visible"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['shopping:goodsType:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Plus"
            v-if="!scope.row.parentId"
            @click="handleAddChild(scope.row)"
            >添加子级</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['shopping:goodsType:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品类型对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      :width="dialogWidth"
      append-to-body
    >
      <el-form ref="goodsTypeRef" :model="form" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="类型名称" prop="typeName">
              <el-input v-model="form.typeName" placeholder="请输入类型名称" />
            </el-form-item>
          </el-col>
          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="父级类型" prop="parentId">
              <el-tree-select
                v-model="form.parentId"
                :data="parentTypeOptions"
                :props="{ value: 'id', label: 'typeName', children: 'children' }"
                placeholder="请选择父级类型"
                clearable
                check-strictly
                :render-after-expand="false"
                v-if="(form.id || !isEditMode) && form.parentId"
              />
              <el-input 
                v-model="parentTypeName" 
                placeholder="父级类型" 
                readonly 
                v-else-if="form.parentId"
              />
              <el-input 
                v-model="parentTypeName" 
                placeholder="一级分类无需选择父级类型" 
                readonly 
                v-else
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="GoodsType">
import {
  listGoodsType,
  getGoodsType,
  delGoodsType,
  addGoodsType,
  updateGoodsType,
} from "@/api/shopping/goodsType";

const { proxy } = getCurrentInstance();

const goodsTypeList = ref([]);
const parentTypeOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const isEditMode = ref(false);
const parentTypeName = ref("");
const tableRef = ref(null); // 添加表格引用
const tableKey = ref(0); // 添加表格key用于强制重新渲染

// 列显隐信息
const columns = ref([
  { key: 0, label: `类型名称`, visible: true },
  { key: 1, label: `ID`, visible: true },
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    typeName: null,
    level: 1,
    parentId: null,
  },
  rules: {
    typeName: [
      { required: true, message: "类型名称不能为空", trigger: "blur" }
    ]
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 清理表格缓存 */
function clearTableCache() {
  // 通过改变key来强制重新渲染整个表格，清除所有懒加载缓存
  tableKey.value++;
  console.log('已清理表格缓存，新的key:', tableKey.value);
}

/** 查询商品类型列表 */
function getList() {
  goodsTypeList.value = []
  loading.value = true;
  
  // 清理表格缓存
  clearTableCache();
  
  listGoodsType(queryParams.value).then((response) => {
    console.log('获取到的所有数据:', response.data);
    // 处理树形数据，只显示一级数据，并为有子节点的数据添加hasChildren标识
    const allData = response.data;
    
    // 调试：显示所有数据的parentId信息
    console.log('数据parentId分析:');
    allData.forEach(item => {
      console.log(`ID: ${item.id}, 名称: ${item.typeName}, parentId: ${item.parentId}, parentId类型: ${typeof item.parentId}`);
    });
    
    // 更严格的过滤逻辑：只显示真正的父级数据（parentId为null、undefined、空字符串或0）
    const parentData = allData.filter(item => {
      const parentId = item.parentId;
      return parentId === null || parentId === undefined || parentId === '' || parentId === 0 || parentId === '0';
    });
    console.log('过滤后的父级数据:', parentData);
    
    // 为有子节点的父级数据添加hasChildren标识
    parentData.forEach(item => {
      const hasChildren = allData.some(child => {
        // 确保类型匹配，将数字转换为字符串进行比较
        const childParentId = child.parentId ? child.parentId.toString() : '';
        const itemId = item.id ? item.id.toString() : '';
        const result = childParentId === itemId;
        if (result) {
          console.log(`找到子节点: 父ID=${itemId}, 子ID=${child.id}, 子parentId=${childParentId}`);
        }
        return result;
      });
      if (hasChildren) {
        item.hasChildren = true;
        console.log(`ID ${item.id} 有子节点`);
      }
    });
    
    goodsTypeList.value = parentData;
    total.value = response.total;
    loading.value = false;
  });
}

/** 懒加载子节点 */
function loadNode(row, treeNode, resolve) {
  const parentId = row.id;
  console.log('加载子节点，父级ID:', parentId);
  
  // 确保parentId是数字类型，并添加时间戳避免缓存
  const queryParams = { 
    parentId: Number(parentId),
    _t: Date.now() // 添加时间戳避免缓存
  };
  console.log('查询参数:', queryParams);
  
  listGoodsType(queryParams).then((response) => {
    const children = response.data || [];
    console.log('获取到的子节点数据:', children);
    
    // 过滤出真正属于当前父级的子节点
    const filteredChildren = children.filter(child => {
      const childParentId = child.parentId;
      const currentParentId = parentId;
      
      // 确保类型匹配进行比较
      const childParentIdStr = childParentId ? childParentId.toString() : '';
      const currentParentIdStr = currentParentId ? currentParentId.toString() : '';
      
      const isChild = childParentIdStr === currentParentIdStr;
      if (isChild) {
        console.log(`确认子节点: 父ID=${currentParentIdStr}, 子ID=${child.id}, 子parentId=${childParentIdStr}`);
      }
      return isChild;
    });
    
    console.log('过滤后的子节点数据:', filteredChildren);
    
    // 为子节点也添加hasChildren标识（如果有更深层的子节点）
    filteredChildren.forEach(child => {
      // 检查是否有更深层的子节点
      child.hasChildren = false; // 暂时设置为false，如果需要可以再次调用API检查
    });
    
    resolve(filteredChildren);
  }).catch((error) => {
    console.error('加载子节点失败:', error);
    resolve([]);
  });
}

/** 获取父级类型选项 */
function getParentTypeOptions() {
  return listGoodsType({}).then((response) => {
    // 只显示一级分类（parentId为null、undefined、空字符串或0）作为父级选项
    parentTypeOptions.value = response.data.filter(item => {
      const parentId = item.parentId;
      return parentId === null || parentId === undefined || parentId === '' || parentId === 0 || parentId === '0';
    }) || [];
    console.log('父级类型选项:', parentTypeOptions.value);
    return parentTypeOptions.value;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  isEditMode.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    typeName: null,
    level: 1,
    parentId: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
  };
  parentTypeName.value = "";
  proxy.resetForm("goodsTypeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  isEditMode.value = false;
  parentTypeName.value = "";
  form.value.parentId = null; // 确保一级分类的parentId为空
  
  // 重新获取最新的父级类型选项
  getParentTypeOptions();
  
  open.value = true;
  title.value = "添加商品类型";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getGoodsType(_id).then((response) => {
    form.value = response.data;
    isEditMode.value = true;
    
    // 重新获取最新的父级类型选项
    getParentTypeOptions().then(() => {
      // 如果是子级分类，获取父级类型名称
      if (form.value.parentId) {
        const parentType = parentTypeOptions.value.find(item => Number(item.id) === form.value.parentId);
        parentTypeName.value = parentType ? parentType.id+'' : '';
        form.value.parentId = parentType ? parentType.id : '';
        console.log('父级类型名称:', parentTypeName.value);
      } else {
        parentTypeName.value = '';
      }
      
      open.value = true;
      title.value = "修改商品类型";
    });
  });
}

/** 添加子级按钮操作 */
function handleAddChild(row) {
  reset();
  isEditMode.value = false;
  form.value.parentId = row.id;
  parentTypeName.value = row.typeName;
  
  // 重新获取最新的父级类型选项
  getParentTypeOptions();
  
  open.value = true;
  title.value = "添加子级商品类型";
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["goodsTypeRef"].validate((valid) => {
    if (valid) {
      // 检查是否存在重复的类型名称
      const checkDuplicate = () => {
        return listGoodsType({ typeName: form.value.typeName }).then((response) => {
          const existingTypes = response.data || [];
          const duplicate = existingTypes.find(item => {
            // 排除当前编辑的记录
            if (form.value.id && item.id === form.value.id) {
              return false;
            }
            // 检查名称是否相同且parentId相同
            return item.typeName === form.value.typeName && 
                   item.parentId === form.value.parentId;
          });
          
          if (duplicate) {
            proxy.$modal.msgError(`已存在相同的类型名称"${form.value.typeName}"`);
            return false;
          }
          return true;
        });
      };
      
      checkDuplicate().then((isValid) => {
        if (isValid) {
          if (form.value.id != null) {
            updateGoodsType(form.value).then((response) => {
              proxy.$modal.msgSuccess("修改成功");
              open.value = false;
              // 清理缓存并重新加载数据
              clearTableCache();
              getList();
            });
          } else {
            addGoodsType(form.value).then((response) => {
              proxy.$modal.msgSuccess("新增成功");
              open.value = false;
              // 清理缓存并重新加载数据
              clearTableCache();
              getList();
            });
          }
        }
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除商品类型编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delGoodsType(_ids);
    })
    .then(() => {
      // 清理缓存并重新加载数据
      clearTableCache();
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 刷新缓存按钮操作 */
function handleRefresh() {
  clearTableCache();
  getList();
  proxy.$modal.msgSuccess("缓存已刷新");
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "shopping/goodsType/export",
    {
      ...queryParams.value,
    },
    `goodsType_${new Date().getTime()}.xlsx`
  );
}

getList();
getParentTypeOptions();

/** 动态计算字段数 **/
const fieldCount = ref(0);

onMounted(() => {
  // 统计表单字段数量
  fieldCount.value = ["typeName", "level", "parentId", "remark"].length;
});

const isTwoColumnForm = computed(() => fieldCount.value > 8);
const dialogWidth = computed(() => (isTwoColumnForm.value ? "60vw" : "500px"));
</script>

<style scoped>
.el-table .el-table__expand-icon {
  margin-right: 8px;
}

.el-table .el-table__expand-icon .el-icon {
  font-size: 12px;
}
</style>
